const { putOSS } = require('../utils/aliyunOss');
const ResultHandler = require('../utils/ResultHandler');
const crypto = require('crypto');

// 单文件上传
module.exports.uploadSingleFile = async (req, res, next) => {
    const { file, type } = req.body;

    // 生成唯一的文件名，避免冲突
    const fileName = `${Date.now()}-${crypto.randomBytes(4).toString('hex')}.${type}`;
    let fileData = file;

    try {
        // 针对 Base64 编码文件进行处理
        if (/^data:image\/[^;]+;base64,/.test(file)) {
            const base64Data = file.replace(/^data:image\/[^;]+;base64,/, "");
            fileData = Buffer.from(base64Data, "base64");
        }

        // 上传到 OSS
        const { res: response, url } = await putOSS(fileName, fileData);

        // 成功上传处理
        if (response.status === 200) {
            return res.json(ResultHandler.success({ url }));
        }

        // 上传失败处理
        return res.json(ResultHandler.error("Failed to upload"));

    } catch (err) {
        next(err);
    }
}
